package com.cskaoyan.market.service.wx.impl;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.service.wx.WxAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName WxAuthServiceImpl
 * @Description
 * @Author MZ
 * @Date 2023/5/19 17:30
 */
@Service
public class WxAuthServiceImpl implements WxAuthService {

    @Autowired
    MarketUserMapper marketUserMapper;

    @Override
    public String checkPasswordByUsername(String username) {
        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.or().andUsernameEqualTo(username);
        MarketUser user = marketUserMapper.selectOneByExample(marketUserExample);
        return user.getPassword();
    }

    @Override
    public MarketUser getUserByUsername(String username) {
        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.or().andUsernameEqualTo(username);
        MarketUser user = marketUserMapper.selectOneByExample(marketUserExample);
        return user;
    }

    @Override
    public Integer registerUser(String username, String password, String mobile) {
        MarketUser marketUser = new MarketUser();
        marketUser.setUsername(username);
        marketUser.setNickname(username);
        marketUser.setPassword(password);
        marketUser.setMobile(mobile);
        marketUser.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");
        marketUser.setAddTime(LocalDateTime.now());
        marketUser.setUpdateTime(LocalDateTime.now());

        // 判断用户名是否重复
        MarketUserExample userExample = new MarketUserExample();
        userExample.or().andDeletedEqualTo(false).andUsernameEqualTo(username);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(userExample);
        if (marketUsers.size() > 0) {
            // 重复
            return -1;
        }
        int row = marketUserMapper.insertSelective(marketUser);
        return row;
    }

    @Override
    public int reset(String mobile, String password) {
        MarketUser user = new MarketUser();
        user.setPassword(password);
        user.setUpdateTime(LocalDateTime.now());
        MarketUserExample userExample = new MarketUserExample();
        userExample.or().andDeletedEqualTo(false).andMobileEqualTo(mobile);
        int row = marketUserMapper.updateByExampleSelective(user, userExample);
        return row;
    }
}
